package com.zh.mediacommon.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.zh.mediacommon.constant.AliPayConstant;
import com.zh.mediacommon.ecxeption.AliPayException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class QRCodeUtil {

    /**
     * 生成二维码并返回Base64编码的图片
     *
     * @param content 二维码内容
     * @param width   图片宽度
     * @param height  图片高度
     * @return Base64编码的图片
     */
    public static String generateQRCode(String content, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);

            // 将图片转换为Base64编码
            return Base64.getEncoder().encodeToString(outputStream.toByteArray());
        } catch (WriterException | IOException e) {
            e.printStackTrace();
            throw new AliPayException(AliPayConstant.GENERATE_QR_CODE_ERROR);
        }
    }
}